package rms.mall.server.domain.typehandler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;


public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<T> ts, JdbcType jdbcType) throws SQLException {
        if (CollectionUtils.isEmpty(ts)) {
            preparedStatement.setString(i, null);
            return;
        }
        preparedStatement.setString(i, ts.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (StringUtils.isBlank(resultSet.getString(s)) || resultSet.wasNull()) {
            return Lists.newArrayList();
        }
        String[] split = resultSet.getString(s).split(",");
        return convertList(Lists.newArrayList(split));
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if (StringUtils.isBlank(resultSet.getString(i)) || resultSet.wasNull()) {
            return Lists.newArrayList();
        }
        String[] split = resultSet.getString(i).split(",");
        return convertList(Lists.newArrayList(split));
    }

    @Override
    public List<T> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        if (StringUtils.isBlank(callableStatement.getString(i)) || callableStatement.wasNull()) {
            return Lists.newArrayList();
        }
        String[] split = callableStatement.getString(i).split(",");
        return convertList(Lists.newArrayList(split));
    }

    protected abstract List<T> convertList(List<String> stringList);

}
